package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mff
 * @date 2022/6/5 0:16
 * @mood happy
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
//        获取表单的用户名
        String username = employee.getUsername();
        LambdaQueryWrapper<Employee> employeeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        employeeLambdaQueryWrapper.eq(Employee::getUsername, username);
        Employee one = employeeService.getOne(employeeLambdaQueryWrapper);
//        开始判断
        log.info("该用户不存在");
        if (one == null) {
//            提示用户信息不存在
            return R.error("该用户不存在");
        }
//        如果用户信息存在，查看密码是否正确
        String password = employee.getPassword();   //用户输入的密码
        String password1 = one.getPassword();       //数据库内的密码
//        给数据库的密码进行加密后再比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        boolean result = password.equals(password1);
        log.info("用户名或者密码错误");
        if (!result) {
            return R.error("账号或者密码错误");
        }

        log.info("该用户已禁用");
        if (one.getStatus() == 0) {
            return R.error("该用户已禁用");
        }
//        将用户信息存入到服务器,并且将对象的密码改为空
        log.info("登录成功");
        one.setPassword(null);
        session.setAttribute("employee", one.getId());
        return R.success(one);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        log.info("退出成功");
        session.invalidate();
        return R.success(null);
    }

    //    添加用户功能
    @PostMapping
    public R<String> saveEmployee(@RequestBody Employee employee,HttpSession session) {

        log.info("开始添加用户");
//        设置默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        从线程中获得用户id
/*        Long userId = (Long) session.getAttribute("employee");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateUser(userId);
        employee.setCreateUser(userId);*/
        employeeService.save(employee);
        return R.success(employee.getUsername() + "添加成功");
    }

    @GetMapping("/page")
    public R<Map<String, Object>> page(int page, int pageSize, String name) {
//          创建分页器
        Page page1 = new Page(page, pageSize);
//        创建条件查询器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
//        条件查询
        queryWrapper.like(StringUtils.isNotBlank(name), Employee::getName, name);
//        添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        employeeService.page(page1, queryWrapper);
        List records = page1.getRecords();
        int total = (int)page1.getTotal();

        Map data = new HashMap();
        data.put("records", records);
        data.put("total", total);

        return R.success(data);
    }

    @PutMapping
    public R<String> updateEmployee(@RequestBody Employee employee,HttpSession session) {
//        需要修改员工的修改时间、更新用户
//        获取当前用户的id
/*        Long userId = (Long) session.getAttribute("employee");
        employee.setUpdateUser(userId);
        employee.setUpdateTime(LocalDateTime.now());*/
        employeeService.updateById(employee);
        return R.success("添加成功");
    }

    //    根据ID查询员工信息,用于回显数据
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id) {
        Employee byId = employeeService.getById(id);
        if (byId!=null){
            return R.success(byId);
        }
        return R.error("该用户不存在");
    }



}
